﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IndicoInterface;
using CommonWFLibrary;
using System.Workflow.Runtime;
using System.Threading;
using DeepTalkWF;
using System.IO;

namespace FullMeetingRender
{
    class Program
    {
        /// <summary>
        /// This program will attempt to run a full meeting render in a single workflow.
        /// This shouldn't be run often -- but it does do a full chain test and make
        /// everything is talking to itself correctly.
        /// 
        /// No crash protection is built in! Uses a single workflow type to do this.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            ///
            /// First step is to come up with the XML for a particular meeting!
            /// 

            AgendaInfo info = new AgendaInfo("http://indico.cern.ch/conferenceDisplay.py?showSession=all&showDate=all&view=xml&fr=no&confId=a042880");
            StringWriter sr = new StringWriter();
            info.Seralize(sr);

            ///
            /// Some temp directoris for output
            /// 

            DirectoryInfo tempDir = new DirectoryInfo(".\\tempFiles");
            DirectoryInfo outputDir = new DirectoryInfo(".\\meeting");

            ///
            /// Run the WF... :-)
            /// 

            var result = RunWFByType(typeof(RenderConference),
                new Dictionary<string, object> {
                { "AgendaInfo", sr.GetStringBuilder().ToString() },
                {"TempDirectory", tempDir},
                {"MeetingOutputDirectory", outputDir}
                });
        }

        /// <summary>
        /// Run a test, throw exceptions back to user.
        /// </summary>
        /// <param name="wfActivity"></param>
        /// <param name="dict"></param>
        public static Dictionary<string, object> RunWFByType(Type wfActivity, Dictionary<string, object> dict)
        {
            using (WorkflowRuntime runtime = new WorkflowRuntime())
            using (AutoResetEvent reset = new AutoResetEvent(false))
            {
                Exception exp = null;
                Dictionary<string, object> r = null;
                runtime.WorkflowCompleted += (o, args) => { r = args.OutputParameters; reset.Set(); };
                runtime.WorkflowTerminated += (o, args) => { exp = args.Exception; reset.Set(); };

                LongRunningActivityBase.RegisterService(runtime);
                runtime.StartRuntime();

                WorkflowInstance instance;
                instance = runtime.CreateWorkflow(wfActivity, dict);
                instance.Start();
                reset.WaitOne();

                if (exp != null)
                {
                    throw exp;
                }

                return r;
            }
        }
    }
}
